package com.exam.master.model.main.view;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.exam.commonbiz.base.BaseActivity;
import com.exam.commonbiz.base.BaseViewModel;
import com.exam.commonbiz.base.BasicApplication;
import com.exam.commonbiz.config.ConfigSP;
import com.exam.commonbiz.event.IdentityExpiredEvent;
import com.exam.commonbiz.event.NewMessageEvent;
import com.exam.commonbiz.push.PushHelper;
import com.exam.commonbiz.util.AppManager;
import com.exam.commonbiz.util.Constant;
import com.exam.commonbiz.util.SharedPreferencesUtils;
import com.exam.commonbiz.util.ToastUtil;
import com.exam.master.R;
import com.exam.master.databinding.ActivityMainBinding;
import com.exam.master.model.login.LoginActivity;
import com.exam.master.model.main.adapter.IncomeTabFragmentAdapter;
import com.exam.master.model.main.bean.IncomeMenuInfo;
import com.google.android.material.tabs.TabLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity<BaseViewModel, ActivityMainBinding> {

    private List<Fragment> mFragmentList;
    private static boolean isExit = false;
    private List<IncomeMenuInfo> mIncomeMenuInfoList;
    private IncomeTabFragmentAdapter mIncomeTabFragmentAdapter;
    private HomeMessageFragment homeMessageFragment;
    private HomePersonalFragment mHomePersonalFragment;

    public static void start(Context context) {
        Intent starter = new Intent(context, MainActivity.class);
        context.startActivity(starter);
    }

    @Override
    public void initData() {

        if (Constant.uploadDeviceToken == false) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            PushHelper.init(getApplicationContext());
                        }
                    }).start();
                }
            }, 2000);
        }
        binding.includeTitle.ivback.setVisibility(View.INVISIBLE);
        binding.includeTitle.tvTitle.setText("消息");
        initViewPager();
        initTabLayout();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    protected boolean isUseBlackFontWithStatusBar() {
        return true;
    }

    /**
     * 更改状态栏颜色，只有非全屏模式下有效
     */
    public int getStatusBarColor() {
        return R.color.color_bg;
    }

    @Override
    public boolean useEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNewMessageEvent(NewMessageEvent newMessageEvent) {
        if (homeMessageFragment != null) {
            homeMessageFragment.loadData();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onIdentityExpiredEvent(IdentityExpiredEvent identityExpiredEvent) {
        ToastUtil.showLongToastCenter("登陆已过期,请重新登陆");
        BasicApplication.logout();
        LoginActivity.start(context);
    }

    private void initViewPager() {
        //把Fragment添加到List集合里面
        mFragmentList = new ArrayList<>();
        mIncomeMenuInfoList = new ArrayList<>();

        IncomeMenuInfo incomeMenuInfoSort = new IncomeMenuInfo();
        incomeMenuInfoSort.tilte = "消息";
        incomeMenuInfoSort.iconSelect = R.drawable.icon_msg_select;
        incomeMenuInfoSort.iconUnSelect = R.drawable.icon_msg_normal;

        IncomeMenuInfo incomeMenuInfo = new IncomeMenuInfo();
        incomeMenuInfo.tilte = "我的";
        incomeMenuInfo.iconSelect = R.drawable.icon_mine_select;
        incomeMenuInfo.iconUnSelect = R.drawable.icon_mine_normal;

        mIncomeMenuInfoList.add(incomeMenuInfoSort);
        mIncomeMenuInfoList.add(incomeMenuInfo);

        homeMessageFragment = HomeMessageFragment.newInstance();
        mFragmentList.add(homeMessageFragment);
        mHomePersonalFragment = HomePersonalFragment.newInstance();
        mFragmentList.add(mHomePersonalFragment);

        mIncomeTabFragmentAdapter = new IncomeTabFragmentAdapter(getSupportFragmentManager(), mFragmentList, mIncomeMenuInfoList, context);
        binding.viewPager.setAdapter(mIncomeTabFragmentAdapter);
        binding.viewPager.setOffscreenPageLimit(mFragmentList.size());
        binding.tabLayout.setupWithViewPager(binding.viewPager);

        for (int i = 0; i < binding.tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = binding.tabLayout.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(mIncomeTabFragmentAdapter.getTabView(i));
            }
        }
        binding.viewPager.setCurrentItem(0);
        onTabSelectView(binding.tabLayout.getTabAt(0));
    }

    private void initTabLayout() {

        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                onTabSelectView(tab);
                if (tab.getPosition() == 1 && mHomePersonalFragment != null) {
                    mHomePersonalFragment.getUserInfo();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                View view = tab.getCustomView();
                TextView textView = view.findViewById(R.id.tv_title);
                textView.setTextColor(getResources().getColor(R.color.black));
                ImageView imgIcon = view.findViewById(R.id.iv_icon);
                imgIcon.setImageResource(mIncomeMenuInfoList.get(tab.getPosition()).iconUnSelect);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                //再次选中tab的逻辑
            }
        });
    }

    private void onTabSelectView(TabLayout.Tab tab) {
        if (tab.getPosition() == 0) {
            binding.includeTitle.tvTitle.setText("消息");
        } else {
            binding.includeTitle.tvTitle.setText("我的");
        }
        IncomeMenuInfo incomeMenuInfo = mIncomeMenuInfoList.get(tab.getPosition());
        View view = tab.getCustomView();
        TextView textView = view.findViewById(R.id.tv_title);
        textView.setTextColor(getResources().getColor(R.color.color_1296db));
        ImageView imgIcon = view.findViewById(R.id.iv_icon);
        imgIcon.setImageResource(incomeMenuInfo.iconSelect);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void back() {

    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            ToastUtil.showShortToast("再按一次退出程序");
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            AppManager.getAppManager().finishAllActivity();
            System.exit(0);
        }
    }

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };
}